﻿using Microsoft.Xaml.Behaviors.Core;
using Pvf.Core;
using Pvf.Editor.Extensions;
using Pvf.Editor.Models;
using System.Collections.ObjectModel;
using System.Windows.Controls;
using System.Windows.Input;

namespace Pvf.Editor.ViewModels
{
    public class MainWindowViewModel : ViewModelBase
    {
        public IFileExplorer FileExplorer { get; set; }

        /// <summary>
        /// 
        /// </summary>
        public ObservableCollection<FileContainerModel> FileContainers { get; } = new ObservableCollection<FileContainerModel>();

        /// <summary>
        /// 
        /// </summary>
        public ObservableCollection<FileItemModel> Files { get; } = new ObservableCollection<FileItemModel>();

        private FileModelBase _selectedFolder;
        /// <summary>
        /// 
        /// </summary>
        public FileModelBase SelectedFolder
        {
            get => _selectedFolder;
            set
            {
                _selectedFolder = value;
                OnPropertyChanged(nameof(SelectedFolder));
            }
        }

        private FileItemModel _selectedFile;
        /// <summary>
        /// 
        /// </summary>
        public FileItemModel SelectedFile
        {
            get => _selectedFile;
            set
            {
                _selectedFile = value;
                OnPropertyChanged(nameof(SelectedFile));
            }
        }

        public ICommand SelectedItemChangedCommand { get; }

        public MainWindowViewModel()
        {
            FileContainers.Add(ModelExtensions.CreateFileContainer("Assets", null));

            SelectedItemChangedCommand = new ActionCommand(OnSelectedItemChanged);
        }

        private void OnSelectedItemChanged(object obj)
        {
            if (obj is not TreeView treeView)
            {
                return;
            }

            Files.Clear();

            if (treeView.SelectedItem is not FileContainerModel containerModel)
            {
                return;
            }

            //根节点
            if (containerModel == FileContainers[0])
            {
                if (FileExplorer == null)
                {
                    return;
                }
                var files = FileExplorer.GetTopFiles();
                foreach (var file in files)
                {
                    Files.Add(ModelExtensions.CreateFile(file.Name, file));
                }
            }
            else
            {
                //子节点
                var files = containerModel.Handle.GetTopFiles();
                foreach (var file in files)
                {
                    Files.Add(ModelExtensions.CreateFile(file.Name, file));
                }
            }


        }
    }
}
